﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace TouShuShenQi.BlazorCore.Repositorys
{
    /// <summary>
    /// 仓储基础类
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public class BaseRepository<TEntity> : SimpleClient<TEntity> where TEntity : class, new()
    {
        public BaseRepository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null
        {
            if (context == null)
            {
                base.Context = new SqlSugarClient(new ConnectionConfig()
                {
                    DbType = SqlSugar.DbType.Sqlite,
                    InitKeyType = InitKeyType.Attribute,
                    IsAutoCloseConnection = true,
                    ConnectionString = DBConfig.ConnectionString
                });

                base.Context.Aop.OnLogExecuting = (s, p) =>
                {
                    Console.WriteLine(s);
                };
            }
        }

        public new async Task<int> InsertAsync(TEntity entity)
        {
            return await base.Context.Insertable(entity).ExecuteReturnIdentityAsync();
        }
        public async Task<int> InsertAsync(List<TEntity> entitys)
        {
            return await base.Context.Insertable(entitys).ExecuteCommandAsync();
        }


        public new async Task<int> UpdateAsync(TEntity entity)
        {
            return await base.Context.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
        }
        public async Task<int> UpdateAsync(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, TEntity>> content)
        {
            return await base.Context.Updateable(content).Where(predicate).ExecuteCommandAsync();
        }

        public async Task<TEntity> FindEntity(object keyValue)
        {
            return await IQueryable().InSingleAsync(keyValue);
        }
        public async Task<TEntity> FindEntity(Expression<Func<TEntity, bool>> predicate)
        {
            return await IQueryable().FirstAsync(predicate);
        }
        public ISugarQueryable<TEntity> IQueryable()
        {
            return base.Context.Queryable<TEntity>();
        }
        public ISugarQueryable<TEntity> IQueryable(Expression<Func<TEntity, bool>> predicate)
        {
            return IQueryable().Where(predicate);
        }
        public ISugarQueryable<TEntity> IQueryable(string strSql)
        {
            return base.Context.SqlQueryable<TEntity>(strSql);
        }


    }


    public class DBConfig
    {
        private static string GetCurrentProjectPath
        {

            get
            {
                return Environment.CurrentDirectory.Replace(@"\bin\Debug", "");//获取具体路径
            }
        }
        public static string ConnectionString = @"DataSource=" + GetCurrentProjectPath + @"\DataBase.db";
    }
}
